# coding=utf-8

import datetime

import web
from web.utils import storage

import utils
from i18n import _

# 登录状态：登录成功
LOGIN_STATUS_SUCCESS = storage(status = 0, text = _(u'登入成功'))
# 登录状态：无效的Email格式
LOGIN_STATUS_INVALID_EMAIL = storage(status = 1, text = _(u'该E-mail尚未注册，现在就<a href="/account/register">注册</a>吗？'))
# 登录状态：密码无效
LOGIN_STATUS_INVALID_PASSWORD = storage(status = 2, text = _(u'密码错误，请确认后重新输入'))
# 登录状态：无效用户（没有user_info记录）
LOGIN_STATUS_INVALID_USER = storage(status = 3, text = _(u'用户信息无效，登录失败'))

# TODO: 用户相关数据操作
class User(object):
	def __init__(self):
		self.db = web.ctx.db
	
	# TODO: 获取给定email对应用户的内码和密码
	def get_pwd_id_by_email(self, email):
		if email:
			sets = self.db.select('user_auth'
					, { 'email': email }
					, where = 'fEmail = $email'
					, what = 'fid, fPassword')
			if sets:
				return sets[0]

		return None
	
	# 读取给定用户的注册信息(user_info)
	def get_info_by_id(self, uid):
		if uid > 0:
			sets = self.db.select('user_info'
					, { 'fid': uid }
					, where = 'fid = $fid'
					, what = 'fCountry,fRegTime,fLastLoginTime')
			if sets:
				return sets[0]
	
	# TODO: 创建 user_auth 记录
	def create_user_auth(self, email, pwd):
		return self.db.inesrt('user_auth', fEmail = email, fPassword = pwd)
	
	# TODO: 创建 user_info 记录
	def create_user_info(self, uid, country):
		return self.db.insert('user_info'
				, fid = uid
				, fRegTime = web.SQLLiteral('NOW()')
				, fLastLoginTime = web.SQLLiteral('NOW()')
				, fCountry = country)
	
	# TODO: 判断给定email是否已经被注册
	def exists_email(self, email):
		return self.db.query('SELECT EXISTS(SELECT NULL FROM user_auth where fEmail = $email) as dup;'
				, vars = { 'email': email })[0].dup == 1
	
user = User()

# TODO: 用户登录逻辑
def login(email, pwd):
	# 获取用户验证信息
	usr = user.get_pwd_id_by_email(email)
	# 用户是否有效
	if not usr:
		return LOGIN_STATUS_INVALID_EMAIL
	# 密码是否正确
	if utils.cmp_i(utils.md5(pwd), usr.fPassword) != 0:
		return LOGIN_STATUS_INVALID_PASSWORD
	
	# 登录成功
	# 1. 更新最后登录时间
	# 2. 读取用户名称
	# 3. 将用户内吗、名称存入cookie
	uinfo = user.get_info_by_id(usr.fid)
	if uinfo:
		# 保存登录状态
		save_login_state({
					'uid': usr.fid,
					'country': uinfo.fCountry
				})
		# 登录成功
		return LOGIN_STATUS_SUCCESS
	
	# 因为user_info没有相应数据而登录失败
	return LOGIN_STATUS_INVALID_USER

# TODO: 保存登录状态
def save_login_state(logusr):
	web.setcookie('su', utils.encrypt('%(uid)d|%(country)d' % logusr))

# 注册状态：注册成功
REGISTER_STATUS_SUCCESS = storage(status = 0, text = _(u'注册成功'))
# 注册状态：邮箱已注册
REGISTER_STATUS_DUPLICATE_EMAIL = storage(status = 1, text = _(u'抱歉，E-mail已被使用'))
# TODO: 注册用户
def register(ipt):
	# 首先判断邮箱是否已被注册
	if user.exists_email(ipt.email):
		return REGISTER_STATUS_DUPLICATE_EMAIL
	
	return REGISTER_STATUS_SUCCESS
